<template>
  <section>
    <el-upload
      class="avatar-uploader"
      :headers="headers"
      :action="actionUrl"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <el-image v-if="showImage" :src="showImage" class="avatar" fit="cover" />
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </section>
</template>

<script>
import setting from '@/settings';
import { getToken, getClient } from '@/utils/auth';

export default {
    props: {
        imageProps: {
            type: String,
            default: '',
        },
        dir: {
            type: String,
            default: 'editor',
        },
    },
    data() {
        return {
            imageUrl: '',
        };
    },
    computed: {
        showImage() {
            return this.imageProps || this.imageUrl;
        },
        actionUrl() {
            return `${setting.baseURL.KujoMiva}/oss/uploader`;
        },
        headers() {
            return {
                client: getClient(),
                dir: this.dir,
                authorization: `Bearer ${getToken()}`,
            };
        },
    },
    methods: {
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
            this.$emit('success', res);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG && !isPNG) {
                this.$message.error('上传图片只能是 JPG或PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
            }
            return (isJPG || isPNG) && isLt2M;
        },
    },
};
</script>

<style lang="scss">
$baseSize: 100px;
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: $baseSize;
  height: $baseSize;
  line-height: $baseSize;
  text-align: center;
}
.avatar {
  width: $baseSize;
  height: $baseSize;
  display: block;
}
</style>
